package swing.customComp;

import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class JPasswordFieldHintListener implements FocusListener {

    private String hintText;
    private HintJPasswordField passwordField;

    public JPasswordFieldHintListener(HintJPasswordField passwordField, String hintText) {
        this.passwordField = passwordField;
        this.hintText = hintText;
        passwordField.setText(hintText);  //默认直接显示
        passwordField.setForeground(Color.GRAY);
    }

    @Override
    public void focusGained(FocusEvent e) {
        //获取焦点时，清空提示内容
        String temp = passwordField.getRealText();
        passwordField.setHint(false);
        if(temp.equals(hintText)) {
            passwordField.setEchoChar('●');
            passwordField.setText("");
            passwordField.setForeground(Color.BLACK);
        }

    }

    @Override
    public void focusLost(FocusEvent e) {
        //失去焦点时，没有输入内容，显示提示内容
        String temp = passwordField.getRealText();
        if(temp.equals("")) {
            passwordField.setHint(true);
            passwordField.setEchoChar((char)0);
            passwordField.setForeground(Color.GRAY);
            passwordField.setText(hintText);
        }

    }

}
